#include <pthread.h>
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int ticket = 100;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *routine(void *args)
{
    char *id = (char *)args;
    while (1)
    {
        pthread_mutex_lock(&lock);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", id, ticket);
            ticket--;
            pthread_mutex_unlock(&lock);
            usleep(100);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            usleep(100);
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_t tid1, tid2, tid3, tid4;
    pthread_create(&tid1, nullptr, routine, (void *)"thread 1");
    pthread_create(&tid2, nullptr, routine, (void *)"thread 2");
    pthread_create(&tid3, nullptr, routine, (void *)"thread 3");
    pthread_create(&tid4, nullptr, routine, (void *)"thread 4");

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
    return 0;
}